package com.avcompris.util.reflect;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;
import static com.google.common.collect.Iterables.toArray;
import static org.apache.commons.io.FileUtils.iterateFiles;
import static org.apache.commons.lang3.StringUtils.substringBefore;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.avcompris.util.AbstractUtils;

/**
 * utility that load Java classes from file names found in a source directory.
 * 
 * @author David Andriana Copyright Avantage Compris SARL 2009 ©
 */
abstract class AbstractClassTestUtils extends AbstractUtils {

	/**
	 * load Java classes corresponding to file names.
	 * 
	 * @param sourceDir the source directory to parse
	 * @return the Java classes found
	 * @throws ClassNotFoundException 
	 */
	public static Class<?>[] loadFileClasses(
			final File sourceDir) throws ClassNotFoundException {

		nonNullArgument(sourceDir, "sourceDir");

		final Collection<Class<?>> fileClasses = new ArrayList<Class<?>>();

		for (final Iterator<?> it = iterateFiles(sourceDir, new String[]{
			"java"
		}, true); it.hasNext();) {

			final File file = (File) it.next();

			final Class<?> fileClass;

			final StringBuilder sb = new StringBuilder();

			sb.append(substringBefore(file.getName(), "."));

			for (File parent = file.getParentFile(); !sourceDir.equals(parent); parent = parent
					.getParentFile()) {

				sb.insert(0, parent.getName() + '.');
			}

			final String fileClassName = sb.toString();

			fileClass = Class.forName(fileClassName);

			fileClasses.add(fileClass);
		}

		return toArray(fileClasses, Class.class);
	}
}
